<template>
  <div>

    <div style="margin-top: 20px">
      <el-button icon="el-icon-upload" type="primary" @click="upload()">上传文件</el-button>
      <el-button @click="addFolderWindow()" icon="el-icon-folder-add">创建文件夹</el-button>
      <input type="file" @change="filechange($event)" style="display: none" id="upload"></input>
      <el-button-group ref="tools" style="display: none">
        <el-button  icon="el-icon-download"  @click="download()">下载</el-button>
        <el-button  icon="el-icon-share" @click="getUrl()">获取Url</el-button>
        <el-button  icon="el-icon-delete" @click="delObject()">删除</el-button>
        <el-button  icon="el-icon-setting" @click="objectReNameWindow()">重命名</el-button>
      </el-button-group>
    </div>

    <div style="margin-top: 2%;margin-bottom: 2%;">

      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item ><el-link @click="goToPre()">返回上一级</el-link></el-breadcrumb-item>
        <el-breadcrumb-item ><el-link @click="fileIndex()" >文件首页</el-link></el-breadcrumb-item>
        <el-breadcrumb-item v-for="(path,index) in paths" :key="index"><el-link @click="goToPath(index)">{{path}}</el-link></el-breadcrumb-item>
      </el-breadcrumb>

    </div>


    <el-table
      ref="multipleTable"
      :data="tableData"
      v-loading="loading"
      element-loading-text="文件上传中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.6)"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="150">
      </el-table-column>
      <el-table-column
        prop="fileName"
        label="文件名"
        width="450">
        <template slot-scope="scope"><i :style="getStyle(scope.row.fileType)" :class="getIco(scope.row.fileType)" ></i>  <el-link style="margin-bottom: 5%;" @click="clickHref(scope.row.fileName,scope.row.fileType)" type="primary">{{ scope.row.fileName }}</el-link></template>
      </el-table-column>
      <el-table-column
        prop="fileSize"
        label="大小(KB)"
        width="200">
      </el-table-column>
      <el-table-column
        prop="fileLastTime"
        label="最后修改时间"
        width="300"
        show-overflow-tooltip>
      </el-table-column>
    </el-table>
    <!--    点击添加文件夹 弹出该弹窗-->
    <el-dialog :visible.sync="addVisible" width="500px">

      <el-form  label-width="80px" >
        <el-form-item label="文件夹名">
          <el-input v-model="folderName"></el-input>
          <el-button style="margin-top: 20px;" @click="addFolder()">创建文件夹</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <!--    修改文件名 弹出该弹窗-->
    <el-dialog :visible.sync="reVisible" width="500px">

      <el-form  label-width="80px" >
        <el-form-item label="文件夹名">
          <el-input v-model="reName"></el-input>
          <el-button style="margin-top: 20px;" @click="objectReName()">修改文件名</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

  </div>
</template>
<script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.js"></script>
<script>
import global from "./global";
export default {
  name: "Main",
  data(){
    return {
      tableData: [{
        fileName: '视频',
        fileSize: '1024m',
        fileLastTime: '2021-04-19',
        fileType:''
      }],
      multipleSelection: [],
      serverAdress: global.serverAdress,
      paths:[],
      addVisible:false,
      folderName:"",
      reVisible:false,
      reName:"",
      username:"qq123456",
      loading:false
    }

  },
  methods: {
    async download(){
      if (this.multipleSelection.length != 1) {
        this.errMsg("一次只能下载一个文件")
        return;
      }
      let objectUrl = await this.getObjectUrl();
      if(objectUrl==""){
        this.errMsg("获取失败");
        return;
      }

      window.open(objectUrl);

    },
    //处理多个文件删除
    delObject(){
      let _this=this;
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

          let path="",fileNames="";
          //不是删除bucket 将文件名拼接起来传入后台
          for (let i=0;i<_this.paths.length;i++){
            path=path+_this.paths[i]+"/";
          }


          //如果是删除文件夹的话 就加入/
          _this.multipleSelection.forEach(e=>{
            if(e.fileType=="folder"){
              _this.errMsg("删除文件夹内容的全部文件即可删除文件夹")
              return
            }else {
              fileNames=path+e.fileName+","+fileNames;
            }

          })
          //将文件路径的，删除掉
          fileNames=fileNames.substring(0,fileNames.length-1);
          axios.get(this.serverAdress+"/files/objectdelete?bucketName="+this.username+"&objectNames="+fileNames,{headers:{
              "token":this.token
            }})
            .then(function (ret){
              if(ret.data.state){
                _this.successMsg("删除成功");
                _this.refreshTable();
              }

            })




      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });




    },
    //获取到文件上传的内容
    filechange(e){
      let bucketName=this.username;
      let path="";
      for (let i=0;i<this.paths.length;i++){
        path=path+this.paths[i]+"/";
      }

      let _this=this;
      let file = e.srcElement.files[0];
      var form = new FormData();
      form.append("file",file);
      this.loading=true;
      axios.post(this.serverAdress+"/files/objectupload?bucketName="+bucketName+"&path="+path,form,{headers:{
          "token":this.token
        }
      }).then(function (ret){
        _this.loading=false;
        _this.successMsg(ret.data.msg);
        _this.refreshTable();

      });

    },
    //刷新表格
    refreshTable(){
      //  文件上传成功 渲染表格
      let prefix="";
      for (let i=1;i<this.paths.length;i++){
        prefix=prefix+this.paths[i]+"/";
      }
      prefix=prefix.substring(0,prefix.length-1);
      this.paths.length=0;
      this.getObject(this.username,prefix);
    },
    //点击上传文件按钮 fileinput接收到
    upload(){
      document.getElementById("upload").click();
    },
    fileIndex(){
      this.paths=[];
      this.getObject(this.username,"")
    },
    //获取对应文件的样式
    getStyle(type){
      if(type=="folder"){
        return "font-size: 30px;color: orange;";
      }else {
        return "font-size: 30px;";
      }
    },
    //获取对应文件的图标
    getIco(type){

      if(type=="folder"){
        return "el-icon-folder";
      }else if(type=="jpg" || type=="png" || type=="jpeg"){
        return "el-icon-picture-outline"
      }else if(type=="mp4"){
        return "el-icon-video-play"
      }else if(type=="txt" || type=="doc"){
        return "el-icon-document";
      }else {
        return "el-icon-cloudy";
      }
    },
    //点击进入到对应的文件夹
    clickHref(path,type){
      if(type=="folder"){
        this.paths.push(path);

          let prefix="";
          for (let i=0;i<this.paths.length;i++){
            prefix=prefix+this.paths[i]+"/";
          }
          prefix=prefix.substring(0,prefix.length-1);
          this.getObject(this.username,prefix);
        }

    },
    //选择框被选择改变
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if(this.multipleSelection.length!=0){
        this.$refs.tools.$el.style.display='inline-block';
      }else {
        this.$refs.tools.$el.style.display='none';
      }
    },
    //进入指定文件
    goToPath(index){

      this.paths = this.paths.slice(0,index+1);
      let prefix='';
      for (let i=1;i<this.paths.length;i++){
        prefix=prefix+this.paths[i];
      }
      this.getObject(this.username,prefix);

    },
    //文件夹返回上一级
    goToPre(){
      this.paths = this.paths.slice(0,this.paths.length-1);

        let prefix='';
        for (let i=1;i<this.paths.length;i++){
          prefix=prefix+this.paths[i];
        }
        this.getObject(this.username,prefix);


    },
    getObject(bucketName,prefix){
      if(prefix!=''){
        prefix=prefix+"/";
      }
      let _this=this;
      axios.get(this.serverAdress+"/file/getuserfile?userName="+bucketName+"&prefix="+prefix,{headers:{
          "token":this.token
        }}).then(function (ret){
        console.log(ret.data);
        if(ret.data.state){
          _this.tableData=ret.data.data;
        }
      })
    },
    getTypeObject(bucketName,type){

      let _this=this;
      axios.get(this.serverAdress+"/file/getalluserfile?userName="+bucketName,{headers:{
          "token":this.token
        }}).then(function (ret){

        if(ret.data.state){
          let types=[];
          if(type=="png"){
            ret.data.data.forEach(e=>{
              let fileType=e['fileType'];
              if(fileType=="png" || fileType=="jpg" || fileType=="jpeg"){
                types.push(e);
              }
            })
          }else if(type=="mp4"){
            ret.data.data.forEach(e=>{
              let fileType=e['fileType'];
              if(fileType=="mp4"){
                types.push(e);
              }
            })
          }else if(type=="txt"){
            ret.data.data.forEach(e=>{
              let fileType=e['fileType'];
              if(fileType=="txt" || fileType=="doc"){
                types.push(e);
              }
            })
          }


          _this.tableData=types;
        }
      })
    },
    //弹出成功消息
    successMsg(msg) {
      this.$message({
        message: msg,
        type: 'success'
      });
    },
    //弹出失败消息
    errMsg(msg){
      this.$message.error(msg);
    },
    //  添加文件夹弹窗
    addFolderWindow(){
      this.addVisible=true;
    },
    //  处理添加文件
    addFolder(){
      this.addVisible=false;
      // 如果路径为0 则创建bucket
      if(this.paths.length==0){
        let _this=this;
        _this.$http.get(this.serverAdress+"/files/makebecket?bucketName="+this.folderName,{
          headers:{
            "token":this.token
          }
        }).then(function (ret){
          if(ret.data.state){
            _this.successMsg("文件夹创建成功");
            _this.folderName='';
            _this.initFiles();
          }
        })

      }else {
        this.paths.push(this.folderName);
        this.tableData=[];
      }
    },
    //获取文件链接
    async getUrl(){

      if (this.multipleSelection.length != 1) {
        this.errMsg("一次只能获取一个url链接")
        return;
      }
      let objectUrl = await this.getObjectUrl();
      if(objectUrl==""){
        this.errMsg("获取失败");
        return;
      }
      this.setClipBoardData(objectUrl);
      this.successMsg("复制内容已粘贴到剪辑版");

    },
    // 获取链接总方法
    async getObjectUrl(){

      let prefix="";
      for (let i=1;i<this.paths.length;i++){
        prefix=prefix+this.paths[i]+"/";
      }
      prefix=prefix+this.multipleSelection[0].fileName;
      let  ret=await this.$http.get(this.serverAdress+"/files/geturl?bucketName="+this.paths[0]+"&objectName="+prefix,{headers:{
          "token":this.token
        }})

      if(ret.data.state){
        return ret.data.data;
      }else {
        return "";
      }

    },
    //将内容复制到剪辑版
    setClipBoardData(text) {
      var copy = function (e) {
        e.preventDefault();
        if (e.clipboardData) {
          e.clipboardData.setData('text/plain', text);
        } else if (window.clipboardData) {
          window.clipboardData.setData('Text', text);
        }
      }
      window.addEventListener('copy', copy);
      document.execCommand('copy');
      window.removeEventListener('copy', copy);
    },
    //文件重命名点击弹窗
    objectReNameWindow(){
      this.reVisible=true;
    },
    //objectReName
    objectReName(){

      if (this.multipleSelection.length != 1) {
        this.errMsg("一次只能修改一个文件")
        return;
      }
      let path="";
      for (let i=1;i<this.paths.length;i++){
        path=path+this.paths[i]+"/";
      }
      let fileName = this.multipleSelection[0].fileName;
      let objectName=path+fileName;
      //获取文件名后缀
      let index = fileName.lastIndexOf(".");
      let lastName = fileName.substring(index,fileName.length);
      let destName=path+this.reName+lastName;

      let _this=this;
      axios.get(this.serverAdress+"/file/objectrename?bucketName="+this.paths[0]+"&objectName="+objectName+"&reName="+destName,{
        headers:{
          "token":this.token
        }
      }).then(function (ret){
        if(ret.data.state){

          _this.successMsg("修改成功");
          //将弹窗关闭
          _this.reVisible=false;
          //刷新当前表格
          _this.refreshTable();
        }else {
          _this.errMsg("修改失败");
        }
      })



    }
  },
  created() {
    // let token = sessionStorage.getItem("token");
    // if(token==null){
    //   alert("请先登录token再继续操作");
    //   return;
    // }
    // this.token=token;
    // this.getObject("qq123456","");
    // this.getTypeObject("qq123456","txt");
    if(typeof(this.$route.query.type)=="undefined"){
      this.getObject(this.username,"");
    }else {
      this.getTypeObject(this.username,to.query.type)
    }
  },
  watch:{
    $route(to,from){

      if(typeof(to.query.type)=="undefined"){
        this.getObject(this.username,"");
      }else {
        this.getTypeObject(this.username,to.query.type)
      }

    }
  }

}
</script>

<style scoped>

</style>
